/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.persistence.hibernate.questionnaire;

import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.model.questionnaire.AnswerOption;
import com.blandware.atleap.model.questionnaire.Question;
import com.blandware.atleap.persistence.hibernate.core.BaseDAOHibernate;
import com.blandware.atleap.persistence.questionnaire.AnswerOptionDAO;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * <p>Hibernate implementation of AnswerOptionDAO</p>
 * <p><a href="AnswerOptionDAOHibernate.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.6 $ $Date: 2008/06/23 13:24:55 $
 */
public class AnswerOptionDAOHibernate extends BaseDAOHibernate
        implements AnswerOptionDAO {

    // ~ CRUD methods ================================================================

    /**
     * @see com.blandware.atleap.persistence.questionnaire.AnswerOptionDAO#createAnswerOption(com.blandware.atleap.model.questionnaire.AnswerOption, com.blandware.atleap.model.questionnaire.Question)
     */
    public Long createAnswerOption(AnswerOption answerOption, Question question) {
        answerOption.setPosition(getFirstFreePosition(question.getId()));
        question.addAnswerOption(answerOption);
        return (Long) getHibernateTemplate().save(answerOption);
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.AnswerOptionDAO#retrieveAnswerOption(Long)
     */
    public AnswerOption retrieveAnswerOption(Long answerOptionId) {
        return (AnswerOption) getHibernateTemplate().get(AnswerOption.class, answerOptionId);
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.AnswerOptionDAO#updateAnswerOption(com.blandware.atleap.model.questionnaire.AnswerOption, com.blandware.atleap.model.questionnaire.Question)
     */
    public void updateAnswerOption(AnswerOption answerOption, Question question) {
		AnswerOption oldAnswerOption = question.updateAnswerOption(answerOption);
        removeFromCache(oldAnswerOption);
		getHibernateTemplate().update(answerOption);
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.AnswerOptionDAO#deleteAnswerOption(com.blandware.atleap.model.questionnaire.AnswerOption)
     */
    public void deleteAnswerOption(AnswerOption answerOption) {
        getHibernateTemplate().delete(answerOption);
        answerOption.getQuestion().removeAnswerOption(answerOption);
    }

    // ~ Additional methods ================================================================

    /**
     * @see com.blandware.atleap.persistence.questionnaire.AnswerOptionDAO#listAnswerOptions(com.blandware.atleap.common.util.QueryInfo)   
     */
    public PartialCollection listAnswerOptions(QueryInfo queryInfo) {
        String whereClause = new String();
        String initialWhereClause = new String();
        String orderByClause = new String();
        if ( queryInfo != null ) {
            whereClause = queryInfo.getWhereClause();
            orderByClause = queryInfo.getOrderByClause();
            if ( whereClause != null && whereClause.length() != 0 ) {
                initialWhereClause = whereClause;
                whereClause = " and " + whereClause;
            } else {
                whereClause = new String();
                initialWhereClause = new String();
            }
            if ( orderByClause != null && orderByClause.length() != 0 ) {
                orderByClause = " order by " + orderByClause;
            } else {
                orderByClause = " order by o.position ";
            }
        }

        Long questionId = null;
        if ( queryInfo != null ) {
            if ( queryInfo.getQueryParameters() != null ) {
                questionId = (Long) queryInfo.getQueryParameters().get("questionId");
            }
        }
        List list = null;
        Integer total = null;
        ArrayList args = new ArrayList();
        String hqlPart = new String();
        if ( questionId != null ) {
            hqlPart = "from AnswerOption o where (o.question.id = ?) " + whereClause;
            args.add(questionId);
        } else {
            hqlPart = "from AnswerOption o where " + initialWhereClause;
        }
        if ( queryInfo != null && (queryInfo.getLimit() != null || queryInfo.getOffset() != null) ) {
            String hqlForTotal = "select count(o.id) " + hqlPart;
            total = findUniqueIntegerResult(hqlForTotal, args.toArray());
            if ( total == null ) {
                total = new Integer(0);
            }
        }
        // If we don't have any info about the total number of results yet or
        // we know that there's something that will be found, then fetch data
        if ( total == null || total.intValue() > 0 ) {
            String hql = "select o " + hqlPart + orderByClause;
            list = executeFind(hql, queryInfo, args.toArray());
            if ( total == null ) {
                total = new Integer(list.size());
            }
        } else {
            list = new ArrayList();
        }
        return new PartialCollection(list, total);
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.AnswerOptionDAO#moveAnswerOption(com.blandware.atleap.model.questionnaire.AnswerOption, boolean)
     */
    public void moveAnswerOption(AnswerOption answerOption, boolean up) {
        AnswerOption neighbourAnswerOption = null;
        String hql;
        String ownerHql;
        List args;

        Long ownerId = answerOption.getQuestion().getId();
        ownerHql = "and o.question.id = ?";
        if (up) {
            hql = "select max(o.position) from AnswerOption o where o.position < ? ";
        } else {
            hql = "select min(o.position) from AnswerOption o where o.position > ? ";
        }
        String neighbourPositionHql = hql + ownerHql;
        args = new ArrayList();
        args.add(answerOption.getPosition());
        args.add(ownerId);

        Integer neighbourPosition = findUniqueIntegerResult(neighbourPositionHql, args.toArray());
        if (neighbourPosition != null) {
            String neighbourHql = "select o from AnswerOption o where o.position = ? " + ownerHql;
            args = new ArrayList();
            args.add(neighbourPosition);
            args.add(ownerId);
            neighbourAnswerOption = (AnswerOption) findUniqueResult(neighbourHql, args.toArray());
            if (neighbourAnswerOption != null) {
                Integer tempPosition = answerOption.getPosition();
                answerOption.setPosition(neighbourAnswerOption.getPosition());
                neighbourAnswerOption.setPosition(tempPosition);

                getHibernateTemplate().update(answerOption);
                getHibernateTemplate().update(neighbourAnswerOption);
            }
        }
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.AnswerOptionDAO#copyAnswerOption(com.blandware.atleap.model.questionnaire.AnswerOption, com.blandware.atleap.model.questionnaire.Question)
     */
    public AnswerOption copyAnswerOption(AnswerOption answerOption,
                                         Question question) {
        AnswerOption copy = new AnswerOption();

        copy.setTitle(new HashMap(answerOption.getTitle()));
        copy.setPosition(answerOption.getPosition());
        question.addAnswerOption(copy);

        getHibernateTemplate().save(copy);
        return copy;
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.AnswerOptionDAO#getFirstLastOccupiedPositions(Long)
     */
    public Integer[] getFirstLastOccupiedPositions(Long ownerId) {
        ArrayList args = new ArrayList();
        String hql = "select min(o.position), max(o.position) from AnswerOption o where ";
        hql += "o.question.id = ?";
        args.add(ownerId);
        Object[] objs = (Object[]) findUniqueResult(hql, args.toArray());
        Integer[] result = new Integer[2];
        result[0] = (Integer) objs[0];
        result[1] = (Integer) objs[1];
        return result;
    }

    /**
     * Returns the least position available among options with a owner with
     * given ID.
     *
     * @param ownerId ID of question which children will be considered
     * @return the least free position
     */
    protected Integer getFirstFreePosition(Long ownerId) {
        Integer result = getFirstLastOccupiedPositions(ownerId)[1];
        if (result == null) {
            result = new Integer(0);
        } else {
            result = new Integer(result.intValue() + 1);
        }
        return result;
    }
}
